package ajaxjs.admin.PageEditor;

import java.io.FileNotFoundException;
import java.io.IOException;

import ajaxjs.Fso;
import ajaxjs.js.JsEngine;
import ajaxjs.Util;
import ajaxjs.net.Request;

import javax.servlet.http.HttpServletRequest;

public class PageEditor  {
	private final static String startToken = "<!-- Editable AREA|START -->";
	private final static String endToken = "<!-- Editable AREA|END -->";
	
	/**
	 * 根据 页面中可编辑区域之标识，取出来。
	 * 
	 * @param fullFilePath
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String read_jsp_fileContent(String fullFilePath)
			throws FileNotFoundException {
		String jsp_fileContent = null;

		jsp_fileContent = Fso.readFile(fullFilePath);

		int start = jsp_fileContent.indexOf(startToken), end = jsp_fileContent.indexOf(endToken);

		try {
			jsp_fileContent = jsp_fileContent.substring(start + startToken.length(), end);
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("页面文件中没有标记可编辑区域之标识。请参考：" + startToken + "/" + endToken);
			jsp_fileContent = null;
		}
		return jsp_fileContent;
	}
	
	private static String getFullPathByRequestUrl(HttpServletRequest request){
		String fullFilePath = ajaxjs.net.Request.get(request, "url");
		// 转为绝对路径
		fullFilePath = request.getSession().getServletContext().getRealPath(fullFilePath);
		
		if (fullFilePath.indexOf(".jsp") != -1) {
		} else fullFilePath += "/index.jsp"; // 加上 扩展名
		
		if(fullFilePath.indexOf("?") != -1){ // 去掉 url 参数
			fullFilePath = fullFilePath.replaceAll("\\?.*$", "");
		}
		return fullFilePath;
	}

	/**
	 * 小心使用，改方法的权限很大！
	 * @param request
	 * @return
	 */
	public static String read_jsp_fileContent(HttpServletRequest request) {
		String fullFilePath = getFullPathByRequestUrl(request);
		
		try {
			return read_jsp_fileContent(fullFilePath);
		} catch (FileNotFoundException e) {
			return e.getMessage();
		}
	}

	/**
	 * 保存要修改的页面
	 * @param newContent
	 * @throws IOException 
	 */
	public static void save_jsp_fileContent(String fullFilePath, String newContent) throws IOException {
		String jsp_fileContent = "", toDel_fileContent = "";
		
		try {
			jsp_fileContent = Fso.readFile(fullFilePath);
			toDel_fileContent = read_jsp_fileContent(fullFilePath); // 读取旧内容
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(toDel_fileContent != null){
			jsp_fileContent = jsp_fileContent.replace(toDel_fileContent, newContent);
			// 保存新内容
			Fso.writeFile(fullFilePath, jsp_fileContent);
		}else{
			throw new IOException("页面文件中没有标记可编辑区域之标识。请参考： startToken/endTpoken");
		}
	}
	
	
	public static String save_jsp_fileContent(HttpServletRequest request){
		String fullFilePath = getFullPathByRequestUrl(request),
			   newContent = Request.getChinese(request, "content");

		try {
			save_jsp_fileContent(fullFilePath, newContent);
		} catch (final IOException e) {
			e.printStackTrace();
//			out.write("{\"isOk\":false, \"msg\":\" "+  msg + " \"}");
			return new JsEngine().parseObj(new Object() {  
				@SuppressWarnings("unused")
				public Boolean isOk = false;
				@SuppressWarnings("unused")
				public String msg = e.getMessage();
			});
		}
		
		return new JsEngine().parseObj(new Object() {  
			@SuppressWarnings("unused")
			public Boolean isOk = true;
			@SuppressWarnings("unused")
			public String msg = "修改成功";
		});
	}
	
	/**
	 * 解析 url 参数，返回 iframe base tag 所用的地址
	 * @param request
	 * @return
	 */
	public String getIframe_basePath(HttpServletRequest request) {
		String basePath = null;
		// 页面的所在位置，参数不用项目前缀
		String url = request.getParameter("url");

		// 只需要目录，不需要文件名，但传如来的是包含文件名的，所以要截取掉
		if (url.contains(".jsp") || url.contains(".htm")) {
			String[] arr = url.split("/"), newArr = new String[arr.length - 1];
			for (int i = 0; i < (arr.length - 1); i++) {
				newArr[i] = arr[i];
			}

			basePath = request.getContextPath() + "/"; // 加上项目前缀，使其完整
			basePath += Util.stringJoin(newArr, "/");
		}else
			basePath = request.getContextPath() + url;
		
//		System.out.println("99999999999999:"+basePath);
		
		request.setAttribute("basePath", basePath);
		return basePath;
	}
	
	// 包装器
	public String uploadFile(HttpServletRequest request){
		Upload upload = new Upload(request);
		return upload.uploadFile();
	}
	public String delFile(HttpServletRequest request){
		Upload upload = new Upload(request);
		return upload.delFile();
	}
	public String getImgList(HttpServletRequest request){
		Upload upload = new Upload(request);
		return upload.getImgList();
	}
}
